package com.aurora.source.center.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aurora.source.R;
import com.aurora.source.adapter.AddImgAdapter;
import com.aurora.source.base.BaseWhiteToolbarActivity;
import com.aurora.source.center.presenter.AddFlowPresenter;
import com.aurora.source.center.view.IAddFlowView;
import com.aurora.source.home.bean.BatchManagementBean;
import com.aurora.source.home.presenter.BatchManagementPresenter;
import com.aurora.source.home.view.IBatchManagementView;
import com.aurora.source.util.DpPxUtil;
import com.aurora.source.util.SPUtils;
import com.aurora.source.widget.ItemDivider;
import com.aurora.source.widget.RecordDialogEditSureCancel;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author: ww
 * @description:流程记录-新增
 * @date: 2018/9/7
 */
public class AddFlowActivity extends BaseWhiteToolbarActivity<AddFlowPresenter> implements IBatchManagementView, IAddFlowView {
    private static final int SELECT_BATCH = 1001;
    @BindView(R.id.rv_add_img)
    RecyclerView rvAddImg;
    AddImgAdapter addImgAdapter;
    String flowPosition;//添加第几步流程 1,2,3
    String processId;//流程id
    @BindView(R.id.ll_pre_batch)
    LinearLayout llPreBatch;
    BatchManagementPresenter batchManagementPresenter;
    BatchManagementBean.BatchListBean selectBatch;
    @BindView(R.id.tv_pre_batch)
    TextView tvPreBatch;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.et_descrip)
    EditText etDescrip;
    @BindView(R.id.et_opt_person)
    EditText etOptPerson;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.bt_add_flow)
    AppCompatButton btAddFlow;
    private int maxPic = 5;

    @Override
    public AddFlowPresenter attach() {
        batchManagementPresenter = new BatchManagementPresenter(this);
        return new AddFlowPresenter(this);
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_add_flow;
    }

    @Override
    public void initData(@Nullable Bundle bundle) {
        flowPosition = bundle.getString("flowPosition");
        processId = bundle.getString("processId");
    }

    @Override
    public void initView(Bundle savedInstanceState, View contentView) {
        simpleToolbar.setMainTitle("流程记录-新增");
        simpleToolbar.setLeftVisibility(View.VISIBLE);
        addImgAdapter = new AddImgAdapter(this);
        rvAddImg.setAdapter(addImgAdapter);
        rvAddImg.setLayoutManager(new GridLayoutManager(this, 4));
        rvAddImg.addItemDecoration(new ItemDivider().setDividerWith(DpPxUtil.dp2px(this, 2)));
        addImgAdapter.setOnAddImgClickListener(new AddImgAdapter.OnAddImgClickListener() {
            @Override
            public void onAddImgClick() {
                if (maxPic - addImgAdapter.getFiles().size() == 0) {//够了
                    showToast("最多选择5张图片");
                    return;
                }
                showPictureSelector(maxPic - addImgAdapter.getFiles().size(), true);

            }
        });
    }

    @Override
    public void doBusiness() {

    }


    @OnClick({R.id.ll_pre_batch, R.id.bt_add_flow})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_pre_batch:
                Bundle bundle = new Bundle();
                bundle.putString("number", flowPosition);
                gotoActivityForResult(BatchSelectActivity.class, SELECT_BATCH, bundle);
               /* Map<String, String> params = new HashMap<>();
                params.put("userId", (String) SPUtils.get(activity, SPUtils.USER_ID, ""));
                params.put("number", flowPosition);
                batchManagementPresenter.batchManagement(this, params,"1");*/
                break;
            case R.id.bt_add_flow: //添加流程
                if (checkNull()) {
                    return;
                }

                final RecordDialogEditSureCancel recordDialogEditSureCancel = new RecordDialogEditSureCancel(activity);
                recordDialogEditSureCancel.setOnSureClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        recordDialogEditSureCancel.dismiss();
                        initProgressDialog("图片压缩处理中",false,null);
                        List<File> files = addImgAdapter.getFiles();
                        List<byte[]> bytes = new ArrayList<>();
                        if(files!=null&&files.size()>0){
                            for(File e:files){
                                bytes.add(getimage(e.getPath()));
                            }
                        }
                        dismissProgressDialog();
                        Map<String, String> params2 = new HashMap<>();
                        params2.put("userId", (String) SPUtils.get(activity, SPUtils.USER_ID, ""));
                        params2.put("processId", processId);
                        params2.put("batchNo", selectBatch.getBatchNo());
                        params2.put("isMain", "Y");
                        params2.put("processRecordTitle", etTitle.getText().toString());
                        params2.put("processRecordContent", etDescrip.getText().toString());
                        params2.put("createUserName", etOptPerson.getText().toString());
                        params2.put("remark", etRemark.getText().toString());
                        basePresenter.addFlowRecoredBytes(params2, bytes);
                    }
                });
                recordDialogEditSureCancel.show();
                break;
        }

    }

    //图片压缩
    private byte[] getimage(String srcPath) {
        return compressImage(BitmapFactory.decodeFile(srcPath));//进行质量压缩
    }

    private byte[] compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 80;
        while ( baos.toByteArray().length / 1024>300) { //循环判断如果压缩后图片是否大于1m,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 20;//每次都减少20
        }
        image.recycle();
        return baos.toByteArray();
    }



    /**
     * 校验
     *
     * @return
     */
    private boolean checkNull() {

        if (selectBatch == null) {
            showToast("请先选择上级批次");
            return true;
        }

        if (TextUtils.isEmpty(processId)) {
            showToast("流程id为空");
            return true;
        }

        if (TextUtils.isEmpty(etTitle.getText().toString())) {
            showToast("标题为空");
            return true;
        }

        if (TextUtils.isEmpty(etRemark.getText().toString())) {
            showToast("操作事项不能为空");
            return true;
        }

        return false;
    }

    @Override
    public void onBatchManagementSuccess(BatchManagementBean data) {
        final List<BatchManagementBean.BatchListBean> batchListBeanList = data.getBatchList();
        if (batchListBeanList == null) {
            return;
        }
        String strings[] = new String[batchListBeanList.size()];
        for (int i = 0, j = data.getBatchList().size(); i < j; i++) {
            strings[i] = data.getBatchList().get(i).getBatchTitle();
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setSingleChoiceItems(strings, -1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                selectBatch = batchListBeanList.get(which);
                tvPreBatch.setText(selectBatch.getBatchTitle());
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @Override
    public void onBatchManagementFail(String msg) {
        showToast(msg);
    }

    //修改批次成功，未用到
    @Override
    public void onChangeSuccess(String msg) {

    }

    //修改批次失败，未用到
    @Override
    public void onChangeFail(String msg) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            if (resultCode == RESULT_OK) {
                List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                for (LocalMedia e : localMedia) {
                    addImgAdapter.addItem(new File(e.getCutPath()));
                }
            }
        } else if (requestCode == SELECT_BATCH) {
            if (resultCode == RESULT_OK) {
                selectBatch = new BatchManagementBean.BatchListBean();
                selectBatch.setBatchNo(data.getStringExtra("number"));
                selectBatch.setBatchTitle(data.getStringExtra("name"));
                tvPreBatch.setText(selectBatch.getBatchTitle());
            }
        }
    }

    @Override
    public void onAddFlowRecoredSuccess(String msg) {
        showToast(msg);
        hideSoftInput();
        finish();
    }

    @Override
    public void onAddFlowRecoredFail(String msg) {
        showToast(msg);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
